﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Security;
using System.Xml.Linq;
using Orange.Mvc4App.Models;
using Orange.Mvc4App.Infrastructure;

namespace Orange.Mvc4App.Controllers {
    public class SystemController : System.Web.Mvc.Controller {
        //Login
        public ActionResult Login() {
            return View();
        }

        //Login-Post
        [HttpPost]
        //[RequireHttps]
        public ActionResult Login(FormCollection forms) {
            string User = forms["UserName"].ToString();
            string Password = forms["Password"].ToString();
            if (Membership.ValidateUser(User, Password)) {
                FormsAuthentication.SetAuthCookie(User, false);
                //return RedirectToAction("Index", "Customer");
                FormsAuthentication.RedirectFromLoginPage(User, false);
            } else {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
            return View();
        }

        //LogOff
        public void LogOff() {
            Session.Abandon();
            FormsAuthentication.SignOut();
            //return RedirectToAction("Login");
            FormsAuthentication.RedirectToLoginPage();
        }

      

        //Change password
        [Authorize]
        public ActionResult ChangePassword() {
            return View(new ChangePasswordModel());
        }

        //Change password - Post
        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model) {
            if (ModelState.IsValid) {
                bool isSuccess;
                try {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true);
                    isSuccess = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                } catch (Exception) {
                    isSuccess = false;
                }
                if (isSuccess) {
                    Session.Abandon();
                    FormsAuthentication.SignOut();
                    FormsAuthentication.RedirectToLoginPage();
                } else {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }
            return View(model);
        }

        public ActionResult Module() {
            return View();
        }
    }
}
